import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Index from '@/views/myIndex.vue'
import Login from '@/views/myLogin.vue'
import List from '@/views/myList.vue'
import Set from '@/views/mySet.vue'
import Home from '@/views/myHome.vue'
import Edit from '@/views/myEdit.vue'
import store from '@/store'

const COMP_MAP = {
  home: Home,
  list: List,
  set: Set,
  edit: Edit
}

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'index',
    component: Index
    // children: [
    //   {
    //     path: '/home',
    //     name: 'home',
    //     component: Home
    //   }, {
    //     path: '/list',
    //     name: 'list',
    //     component: List,
    //     meta: {
    //       isLogin: true
    //     }
    //   }, {
    //     path: '/set',
    //     name: 'set',
    //     component: Set,
    //     meta: {
    //       isLogin: true
    //     }
    //   }
    // ]
  }, {
    path: '/login',
    name: 'login',
    component: Login
  }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// router.addRoute('index',[])

router.beforeEach(async (to, from, next) => {
  // console.log(to, 'to')

  if (['/login', '/register'].includes(to.path)) {
    next()
    return
  }
  if (!localStorage.getItem('token')) {
    next(`/login?redirectUrl=${encodeURIComponent(to.fullPath)}`)
    return
  }
  if (to?.name === 'index') {
    next('/home')
    return
  }
  if (router.hasRoute(to?.name || '')) {
    next()
    return
  }
  const { isRequested } = (store.state as any).router
  if (!isRequested) {
    const result = await store.dispatch({ type: 'router/asyncRequestRouter' })
    function transformRouter(data: any[], parent: string) {
      data.forEach((item: { name: 'home' | 'list' | 'set', children: any[] }) => {
        const route: any = {
          ...item,
          component: COMP_MAP[item.name]
        }
        router.addRoute(parent, route)
        if (item.children?.length) {
          transformRouter(item.children, item.name)
        }
        return route
      })
    }
    console.log(result, 'result')
    transformRouter(result, 'index')
    // result.forEach((item: { name: 'home' | 'list' | 'set' }) => {
    //   const route: any = {
    //     ...item,
    //     component: COMP_MAP[item.name]
    //   }
    //   router.addRoute('index', route)
    //   return route
    // })
  }

  console.log(router.hasRoute('home'), 'has')

  console.log(router.getRoutes(), 'router')
  // return to.path
  console.log(to, 'path')
  return next({ ...to })
})

export default router
